iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 28
0
Software Development

挑戰 30天內送審一支APP 系列 第 28

UIImagePickerController and Camera (一) ( D day + 27 )

  • 分享至 

  • xImage
  •  

終於要進入主題,這次先來實作如何創建一個button並且開啟 camera

  1. 首先在 < info.plist > 內加入描述 , 這樣才不會再開啟 APP時 crash
  2. 在< AppDelegate,swift >建立一個視窗
var window: UIWindow?
var mainVC: ViewController?
//create a window and display on the screen
window = UIWindow(frame:UIScreen.main.bounds)
//mainVC = ViewController()
//window?.rootViewController = mainVC
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
  1. <ViewController.swift > 新增兩個Delegate
    UIImagePickerControllerDelegate -> 選取圖片完後觸發的事件
    UiNavigationControllerDelegate -> 開啟相機或存取照片時畫面跳轉所用
class ViewController: UIViewController ,UIImagePickerControllerDelegate, UINavigationControllerDelegate
  1. 在 < viewDidLoad > 中 ,創建一個button,在點擊的時候會觸發 camera
var cameraBtn : UIButton = UIButton()
cameraBtn.frame = CGRect(x: (myFullSize.width/2 - 50), y: (myFullSize.height/2 - 30 ), width: 100 , height: 100)
cameraBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
cameraBtn.setTitle("camera", for: .normal)
cameraBtn.setTitleColor(UIColor.green, for: .normal)
cameraBtn.layer.cornerRadius = 10
cameraBtn.backgroundColor = UIColor.red
cameraBtn.addTarget(self, action: #selector(onCameraBtnAction(_:) ), for: UIControlEvents.touchUpInside)

self.view.addSubview(cameraBtn)

其中
cameraBtn.addTarget(self, action: #selector(onCameraBtnAction(_:) ), for: UIControlEvents.touchUpInside)
**當按鈕被觸發(”touchUpInside”) 系統就會呼叫“onCameraBtnAction” 這個function
5. 建立一個switch,當function(“onCameraBtnAction”)經過 button被呼叫後,會去對應的 funcion(“callcamera(1)”),在這邊是檢查這個裝置是否有 camera device,如果有就會繼續執行,如果沒有就會 print (“no camera”)

func callcamera(_ cranberries:Int) {
        let picker: UIImagePickerController = UIImagePickerController()
        switch cranberries {
        case 1:
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
                picker.sourceType = UIImagePickerControllerSourceType.camera
                picker.allowsEditing = true
                picker.delegate = self
                self.present(picker, animated: true, completion: nil)
            }else {
                //print("no camera")
            }
        default:
            print("switch default")
        }
    }
 @objc func onCameraBtnAction(_ sender:UIButton) {
            self.callcamera(1)
        }

其中 “onCameraBtnAction” 因為是被 #select 所呼叫,所以前面要加上 “@objc“才不會報錯

R.I.P
Dolores O’Riordan
1971-2018


上一篇
UITabBarController (一) ( D day + 26 )
下一篇
QR code scanner and AVCaptureSession (一) ( D day + 28 )
系列文
挑戰 30天內送審一支APP 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言